/*
   Copyright (c) 2016-2017 Slamtec Co., Ltd. All Rights Reserved.
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
       http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.csjbot.weedle_auto.Slam.data

import android.graphics.Point
import android.graphics.Rect

import com.csjbot.weedle_auto.Slam.LogUtil

import java.util.Arrays

/**
 * Created by Alan on 10/8/15.
 * RectangleI is Rect in android
 * RectangleF is RectF in android
 */
class MapDataStore {

    var area: Rect? = null
        private set
    private var mapData: ByteArray? = null

    init {
        this.area = Rect(0, 0, 0, 0)
    }

    @Synchronized
    fun update(area: Rect, data: ByteArray) {
        if (mapData == null) {
            this.area = Rect(area)
            mapData = Arrays.copyOf(data, data.size)
        } else {
            expandArea(Rect(area))

            copyBuffer(mapData, this.area, data, area,
                    Point(area.left - this.area!!.left, area.top - this.area!!.top),
                    Point(0, 0), Point(area.width(), area.height()))
        }
    }

    @Synchronized
    fun fetch(area: Rect, buffer: ByteArray) {
        Arrays.fill(buffer, 0.toByte())
        copyBuffer(buffer, area, mapData, this.area, Point(0, 0),
                Point(area.left - this.area!!.left, area.top - this.area!!.top),
                Point(area.width(), area.height()))
    }

    fun expandArea(area: Rect) {
        if (mapData != null) {
            area.union(this.area)

            if (area == this.area) {
                return
            }
        }
        val newBuffer = ByteArray(Math.abs(area.width() * area.height()))
        copyBuffer(newBuffer, area, mapData, this.area,
                Point(this.area!!.left - area.left, this.area!!.top - area.top),
                Point(0, 0), Point(this.area!!.width(), this.area!!.height()))
        this.area = area
        this.mapData = newBuffer
    }

    fun clear() {
        this.area = Rect(0, 0, 0, 0)
        if (mapData != null) {
            mapData = null
        }
    }

    val isEmpty: Boolean
        get() = this.mapData == null

    operator fun get(x: Int, y: Int): Byte {
        return if (x < area!!.left || y < area!!.top || x >= area!!.right || y >= area!!.bottom) {
            0
        } else mapData!![(y - area!!.top) * area!!.width() + (x - area!!.left)]

    }

    companion object {
        private val TAG = "MapDataStore"

        private fun copyBuffer(dest: ByteArray?, destSize: Rect?, src: ByteArray?,
                               srcSize: Rect?, destOffset: Point, srcOffset: Point,
                               dimension: Point) {
            if (dest == null || src == null) {
                return
            }

            if (srcOffset.x < 0) {
                dimension.x += srcOffset.x
                destOffset.x -= srcOffset.x
                srcOffset.x = 0
            }

            if (srcOffset.y < 0) {
                dimension.y += srcOffset.y
                destOffset.y -= srcOffset.y
                srcOffset.y = 0
            }

            if (destOffset.x < 0) {
                dimension.x += destOffset.x
                srcOffset.x -= destOffset.x
                destOffset.x = 0
            }

            if (destOffset.y < 0) {
                dimension.y += destOffset.y
                srcOffset.y -= destOffset.y
                destOffset.y = 0
            }

            val srcRect = Rect(srcOffset.x, srcOffset.y, srcOffset.x + dimension.x,
                    srcOffset.y + dimension.y)
            val destRect = Rect(destOffset.x, destOffset.y, destOffset.x + dimension.x,
                    destOffset.y + dimension.y)

            srcRect.intersect(Rect(0, 0, srcSize!!.width(), srcSize.height()))
            destRect.intersect(Rect(0, 0, destSize!!.width(), destSize.height()))

            if (srcRect.width() < destRect.width()) {
                dimension.x = srcRect.width()
            } else {
                dimension.x = destRect.width()
            }

            if (srcRect.height() < destRect.height()) {
                dimension.y = srcRect.height()
            } else {
                dimension.y = destRect.height()
            }

            if (dimension.x <= 0 || dimension.y <= 0) {
                return
            }

            var destIndex = destRect.top * destSize.width() + destRect.left
            var srcIndex = srcRect.top * srcSize.width() + srcRect.left
            val copySize = dimension.x

            try {
                for (y in 0..dimension.y - 1) {
                    System.arraycopy(src, srcIndex, dest, destIndex, copySize)

                    destIndex += destSize.width()
                    srcIndex += srcSize.width()
                }
            } catch (e: ArrayIndexOutOfBoundsException) {
                LogUtil.e(TAG, "copy buffer array index out of bounds")
            }

        }
    }
}
